package com.kancy.publicapi.web.controller;

import org.apache.commons.codec.binary.Base64;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author kancy
 * @date 2019/12/22 23:16
 **/
@RestController
public class Base64Controller {

    /**
     * base64
     * @return
     */
    @RequestMapping(value = "/base64/{value}", method = {RequestMethod.GET, RequestMethod.POST})
    public String base64(@PathVariable(value = "value", required = false) String value1,
                         @RequestParam(value = "value", required = false) String value2){
        String value = null;
        if (StringUtils.isEmpty(value1) && StringUtils.isEmpty(value2)){
            return "fail：value is empty";
        }
        if (!StringUtils.isEmpty(value1)){
            value = value1;
        }
        if (!StringUtils.isEmpty(value2)){
            value = value2;
        }
        String ret = null;
        try {
            ret = Base64.isBase64(value) ?
                    Base64.encodeBase64String(value.getBytes()):new String(Base64.decodeBase64(value));
        } catch (Exception e) {
            ret = "fail: base64 value is error";
        }
        return ret;
    }

}
